package com.hotau.update.service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.update.vo.UpdateResult;
import com.hotau.util.ConvertUtils;
import com.hotau.util.DialogUtil;
import com.hotau.util.DownloadFileAsyncTask;
import com.hotau.util.HttpUtil;
//import org.jdom.Document;
//import org.jdom.Element;
//import org.jdom.input.SAXBuilder;

public class UpdateService {

	public static final boolean V_RESULT = false;
	public static final String OS = "android";
	private static Timer timer = null;
	public static TimerTask scheuleTask;

	public static int NO_UPDATE = 0;
	public static int NORMAL_UPDATE = 1;
	public static int FORCE_UPDATE = 2;
	public static int ERROR_UPDATE = 3;
	public static boolean SHOW_NO_UPDATE = false;
	public static boolean PROCESSING = false;

	public static void startMonitor(final Context context) {

		PROCESSING = false;

		final MyHandler handler = new MyHandler(context, Looper.getMainLooper());
		timer = new Timer();

		scheuleTask = new TimerTask() {
			@Override
			public void run() {

				// boolean avaiable = myCheckUpdateAvaiable(context);
				// Log.d("mytag", "是否有更新=" + avaiable);
				// if (waiting) {
				// Log.d("mytag", "还没更新完成或正在等用户处理");
				// }
				// if (!waiting && avaiable) {
				// Message msg = new Message();
				// msg.what = NORMAL_UPDATE;
				// handler.sendMessage(msg);
				// }

				if (!PROCESSING) {
					PROCESSING = true;
					Message updateMsg = checkUpdateAvaiable(context);

					if (updateMsg == null) {
						PROCESSING = false;
						return;
					}

					Log.d("mytag", "是否有更新=" + updateMsg.what + " waiting＝"
							+ PROCESSING);
					handler.sendMessage(updateMsg);
				} else {
					Log.d("mytag", "正在处理。。。");
				}

			}

		};
		// 半天执行一次
		timer.schedule(scheuleTask, 0, HotauConstants.UPDATE_PERIOD);
	}

	public static String assembleFalseResult(Context context, int resultXmlId) {
		String result = "";
		try {
			result = ConvertUtils.convertStreamToString(context.getResources()
					.openRawResource(resultXmlId));
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static Message checkUpdateAvaiable(Context context) {
		try {
			String result = "";

			if (V_RESULT) {
				// 组装虚拟结果
				result = assembleFalseResult(context, R.raw.update_resuslt);
			} else {

				String url = assembleUpdateUrl(context) + "&timestamp="
						+ new Date().getTime();

				// result = HttpUtil.doHttp(url, "", HttpUtil.HTTP_GET,
				// HttpUtil.ENCRYP_AND_GZIP);

				String[] params = new String[6];
				params[0] = url;
				params[1] = "";
				params[2] = HttpUtil.UTF8_ENCODING;
				params[3] = HttpUtil.HTTP_GET;
				params[4] = "5000";
				params[5] = "3000";
				result = HttpUtil.doWrapedHttp(context, params);
			}

			UpdateResult updateResult = UpdateService
					.covertUpdateResult(result);

			if (updateResult == null) {
				Log.e("mytag", "获取update信息为空");
				return null;
			}

			Message msg = new Message();
			if (updateResult.error != null && !"".equals(updateResult.error)) {
				Log.e("mytag", "获取update信息出错=" + updateResult.error);
				msg.obj = updateResult.error;
				msg.what = ERROR_UPDATE;
				return msg;
			}

			if (updateResult != null) {
				msg.obj = updateResult.description;

				if (updateResult.forceUpdate()) {
					Log.i("mytag", "获取update信息：强制更新");
					msg.what = FORCE_UPDATE;
				} else if (updateResult.hasNew()) {
					Log.i("mytag", "获取update信息：有新版本");
					msg.what = NORMAL_UPDATE;
				} else {
					Log.i("mytag", "获取update信息：无可用更新");
					msg.what = NO_UPDATE;
				}
			}
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	private static class MyHandler extends Handler {

		private Context context;
		private Dialog noUpdateDialog;
		private Dialog normalDialog;
		private Dialog forceDialog;

		// private boolean agreeForceUpdate = false;

		public MyHandler(final Context context, Looper looper) {
			super(looper);
			this.context = context;

			normalDialog = DialogUtil.getDialog(context,
					R.layout.r_updateokcanceldialogview);
			Button normalDialogBtnOK = (Button) normalDialog
					.findViewById(R.id.ok);
			normalDialogBtnOK.setText("立即更新");
			normalDialogBtnOK.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					normalDialog.dismiss();
					Log.i("mytag", "do update...");
					update(context);
				}
			});
			Button normalDialogBtnCancel = (Button) normalDialog
					.findViewById(R.id.cancel);
			normalDialogBtnCancel.setText("下次更新");
			normalDialogBtnCancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// UpdateService.stopMonitor();
					PROCESSING = false;
					normalDialog.dismiss();
					// ((Activity) context).finish();
				}
			});
			normalDialog.setCancelable(false);
			// normalDialog.setOnDismissListener(new OnDismissListener() {
			// @Override
			// public void onDismiss(DialogInterface dialog) {
			// PROCESSING = false;
			// }
			// });

			forceDialog = DialogUtil.getDialog(context,
					R.layout.r_updateokcanceldialogview);
			Button forceDialogBtnOK = (Button) forceDialog
					.findViewById(R.id.ok);
			forceDialogBtnOK.setText("立即更新");
			forceDialogBtnOK.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					forceDialog.dismiss();
					// agreeForceUpdate = true;
					// waiting = true;
					Log.i("mytag", "do update...");
					update(context);
				}
			});
			Button forceDialogBtnCancel = (Button) forceDialog
					.findViewById(R.id.cancel);
			forceDialogBtnCancel.setText("取消");
			forceDialogBtnCancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					forceDialog.dismiss();
					PROCESSING = false;
					((Activity) context).finish();
				}
			});
			forceDialog.setCancelable(false);

			noUpdateDialog = DialogUtil.getDialog(context,
					R.layout.r_updateokdialogview);
			Button noUpdateDialogBtnOK = (Button) noUpdateDialog
					.findViewById(R.id.ok);
			noUpdateDialogBtnOK.setText("确定");
			noUpdateDialogBtnOK.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					noUpdateDialog.dismiss();
					// agreeForceUpdate = true;
					// waiting = true;
					Log.i("mytag", "no update...");
					PROCESSING = false;
					SHOW_NO_UPDATE = false;
				}
			});
			noUpdateDialog.setCancelable(false);

		}

		@Override
		public void handleMessage(Message message) {

			Log.i("mytag", "接收到消息。。。");
			if (!forceDialog.isShowing() && !normalDialog.isShowing()) {
				if (ERROR_UPDATE == message.what) {
					Log.e("mytag", "更新出错=" + message.obj);
					if (SHOW_NO_UPDATE) {
						((TextView) noUpdateDialog
								.findViewById(R.id.dialog_msg1)).setText("");
						((TextView) noUpdateDialog
								.findViewById(R.id.dialog_msg2))
								.setText(message.obj.toString());
						((TextView) noUpdateDialog
								.findViewById(R.id.dialog_msg3)).setText("");
						noUpdateDialog.show();
					} else {
						PROCESSING = false;
					}
				} else if (FORCE_UPDATE == message.what) {
					Log.i("mytag", "旧版本不能用强制更新");
					// agreeForceUpdate = false;

					String updateinfo = message.obj == null ? ""
							: (String) message.obj;
					((TextView) forceDialog.findViewById(R.id.dialog_msg1))
							.setText("客户端进行了升级");
					((TextView) forceDialog.findViewById(R.id.dialog_msg2))
							.setText("旧版本已不可用，请更新您的客户端。");
					((TextView) forceDialog.findViewById(R.id.dialog_msg3))
							.setText(updateinfo);
					forceDialog.show();
				} else if (NORMAL_UPDATE == message.what) {
					Log.i("mytag", "旧版本能用并提示更新");
					String updateinfo = message.obj == null ? ""
							: (String) message.obj;
					((TextView) normalDialog.findViewById(R.id.dialog_msg1))
							.setText("");
					((TextView) normalDialog.findViewById(R.id.dialog_msg2))
							.setText("客户端进行了升级，请更新您的客户端。");
					((TextView) normalDialog.findViewById(R.id.dialog_msg3))
							.setText(updateinfo);
					normalDialog.show();
				} else {
					Log.i("mytag", "已经是最新版本");
					// do nothing
					if (SHOW_NO_UPDATE) {
						((TextView) noUpdateDialog
								.findViewById(R.id.dialog_msg1)).setText("");
						((TextView) noUpdateDialog
								.findViewById(R.id.dialog_msg2))
								.setText("您的客户端已是最新版本，不需要更新。");
						((TextView) noUpdateDialog
								.findViewById(R.id.dialog_msg3)).setText("");
						noUpdateDialog.show();
					} else {
						PROCESSING = false;
					}
				}
			}

		}
	}

	public static void stopMonitor() {
		if (timer != null) {
			timer.cancel();
		}
	}

	// 　立即更新
	private static void update(final Context context) {

		final DownloadFileAsyncTask task = new DownloadFileAsyncTask(context) {

			@Override
			protected void doPostExecute(String result) {
				PROCESSING = false;
				// deleteOldApp(context);
				updateVersion(context);
			}
		};

		task.execute(new String[] {
				HotauConstants.UPDATE_FILE_URL
						+ HotauConstants.UPDATE_FILE_NAME,
				HotauConstants.UPDATE_FILE_NAME, DownloadFileAsyncTask.PRIVATE });

		task.progressDialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				Log.d("mytag", "progressDialog onDismiss。。。。");
				task.cancel(true);
				PROCESSING = false;
				Log.d("mytag", "progressDialog 强制检查！");
				scheuleTask.run();
			}
		});

	}

	public static void updateVersion(Context context) {
		Log.d("mytag", "执行安装。。。");
		HotauActivity csmbpActivity = HotauActivity.class.cast(context);
		Intent intent = new Intent(Intent.ACTION_VIEW);

		// sdcard
		// File apkFile = new File("/sdcard/" + DaoConsts.UPDATE_FILE_NAME);
		File apkFile = new File(context.getFilesDir(),
				HotauConstants.UPDATE_FILE_NAME);

		intent.setDataAndType(Uri.fromFile(apkFile),
				"application/vnd.android.package-archive");

		csmbpActivity.startActivity(intent);
	}

	public static void deleteOldApp(Context context) {
		Log.d("mytag", "删除本地应用");
		Uri packageURI = Uri.parse("package:com.csair.mbp");
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(uninstallIntent);
	}

	public static String assembleUpdateUrl(Context context) {
		// http://10.108.108.143/CSMBP/data/order/generatetoken.do?
		// deviceid={0}&os={0}&osversion={0}&appversion={0}

		int SDK_INT = android.os.Build.VERSION.SDK_INT;
		Log.d("mytag", "SDK_INT=" + SDK_INT);

		String SDK = android.os.Build.VERSION.SDK;
		Log.d("mytag", "SDK=" + SDK);

		String release = android.os.Build.VERSION.RELEASE;
		Log.d("mytag", "release=" + release);

		StringBuffer url = new StringBuffer(HotauConstants.UPDATE_URL);
		url.append("&deviceid="
				+ HotauConstants.getEncryptedDeviceId(context, true));
		url.append("&os=" + OS);
		url.append("&osversion=" + SDK_INT);
		url.append("&appversion=" + HotauConstants.getAppVersion(context));
		Log.i("mytag", "update url=" + url.toString());
		return url.toString();
	}

	// public static String getTextTrim(Element element, String elementStr) {
	// if (element != null) {
	// Element childElement = element.getChild(elementStr);
	// return childElement == null ? null : childElement.getTextTrim();
	// } else {
	// return null;
	// }
	//
	// }

	public static UpdateResult covertUpdateResult(String resultResponse) {

		UpdateResult updateResult = new UpdateResult();

		// if (resultResponse == null || resultResponse.equals("")) {
		// updateResult.error = "没有获取升级信息，请检查网络等状况。";
		// return updateResult;
		// }
		//
		// StringReader stringReader = new StringReader(resultResponse);
		// try {
		// Log.i("mytag", "result=" + resultResponse);
		// InputSource inputSource = new InputSource(stringReader);
		// // 构建SAXBuilder对象
		// SAXBuilder builder = new SAXBuilder();
		// // 构建Document对象
		// Document doc = builder.build(inputSource);
		// // 获取根元素
		// Element root = doc.getRootElement();
		//
		// // 查看是否有异常信息
		// Element errMsgElement = root.getChild("MESSAGE");
		// if (errMsgElement != null) {
		// updateResult.error = errMsgElement.getTextTrim();
		// } else {
		// // 正式开始获取数据
		// String versionStates = getTextTrim(root, "VERSIONSTATES");
		// String description = getTextTrim(root, "DESCRIPTION");
		//
		// updateResult.versionStates = versionStates;
		// updateResult.description = description;
		// }
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// return updateResult;
		// } finally {
		// try {
		// // 关闭
		// stringReader.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//
		// }
		return updateResult;

	}

}
